package com.ctg.behavior.calc.impala.transfer.funnel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ctg.behavior.calc.common.CtCalcDate;
import com.ctg.behavior.calc.common.CtSQLConsts;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.report.funnel.CtCalcFunnelStepReport;
import com.ctg.behavior.calc.utils.CtCalcDaysUtils;
import com.ctg.behavior.common.calc.CtCalc;
import com.ctg.behavior.utils.CtDateUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtFunnelStepUnionTransfer {

	// KEY: step + "@" + day
	private static ThreadLocal<Map<String, String>> indexedStepDayFilterSQL = new ThreadLocal<>();

	@Autowired
	private CtFunnelStepTransfer stepTransfer;
	@Autowired
	private CtFunnelStepUserIdsTransfer stepUserIdsTransfer;

	public void resetIndexedThreadLocal() {
		indexedStepDayFilterSQL.set(new HashMap<String, String>());
	}

	public String doTransfer(CtCalc calcObject, CtCalcFunnelStepReport lastFunnelStep) {
		if (!(calcObject instanceof CtCalcFunnelStepReport)) {
			log.warn("calcObject is not CtCalcFunnelStepReport, class={}", calcObject.getClass());
			return "";
		}
		CtCalcFunnelStepReport funnelStep = (CtCalcFunnelStepReport) calcObject;

		StringBuilder impalaSQL = new StringBuilder();

		List<CtCalcDate> calcDays = CtCalcDaysUtils.listCalcDays(funnelStep.getFromDate(), funnelStep.getToDate());
		for (int index = 0; index < calcDays.size(); index++) {
			CtCalcDate calcDate = calcDays.get(index);
			String calcDateFrom = CtDateUtils.dateToString(calcDate.getFromDate(), CtDateUtils.YYYY_MM_DD);
			String calcDateTo = CtDateUtils.dateToString(calcDate.getToDate(), CtDateUtils.YYYY_MM_DD);

			String lastUserIdsSQL = indexedStepDayFilterSQL.get().get(calcDateFrom);

			// 1.1拼接上步的UserIdsSQL
			CtSQLParam lastUserIdsSQLParam = CtSQLParam.createFilterParam(lastUserIdsSQL);
			lastUserIdsSQLParam.addParam(CtSQLConsts.KEY_FILTER_DATE_FROM, calcDateFrom);
			lastUserIdsSQLParam.addParam(CtSQLConsts.KEY_FILTER_DATE_TO, calcDateTo);
			lastUserIdsSQL = stepUserIdsTransfer.doTransfer(lastFunnelStep, lastUserIdsSQLParam);
			indexedStepDayFilterSQL.get().put(calcDateFrom, lastUserIdsSQL);

			// 1.2接接本步的SQL
			CtSQLParam sqlParam = CtSQLParam.createFilterParam(lastUserIdsSQL);
			sqlParam.addParam(CtSQLConsts.KEY_FILTER_DATE_FROM, calcDateFrom);
			sqlParam.addParam(CtSQLConsts.KEY_FILTER_DATE_TO, calcDateTo);
			String oneUnionSQL = stepTransfer.doTransfer(funnelStep, sqlParam);
			if (index > 0) {
				impalaSQL.append(" UNION ");
			}
			impalaSQL.append(oneUnionSQL);
		}

		return impalaSQL.toString();
	}

}
